<?php

class WeixinApi extends ApiBase
{
	private $mysql = null;

	public function __construct()
	{
		parent::__construct();
		$this->mysql = n_api('mysql')->cname('weixin');
		$this->redis = n_api('redis')->scrapy;
	}
	public function addWx($str) {
		if (is_array($str)) {
			$weixinArr = $str;
			$weixinInMysql = $this->getAllWeixin();

			$allWeixin = [];
			$bizArr = [];
			foreach ($weixinArr as $key => $weixinUrl) {
				$urlParse = parse_url($weixinUrl, PHP_URL_QUERY);
				parse_str($urlParse);
				if (in_array($__biz, $bizArr) || array_key_exists($__biz, $weixinInMysql))
					continue;
				else
					$bizArr[] = $__biz;

				$content = $this->getArticleByUrl($weixinUrl);
				$weixinInfo = $this->getArticleWeixinInfo($content);

				$weixinInfo['biz'] = $__biz;
				$weixinInfo['ctime'] = time();
				$weixinInfo['wxname'] = $weixinInfo['nickname'];
				$weixinInfo['description'] = $weixinInfo['desc'];
				
				unset($weixinInfo['nickname']);
				unset($weixinInfo['desc']);
				if ($weixinInfo['wxid'] == '')
					continue;
				$allWeixin[] = $weixinInfo;

				if ($key > 0)
					usleep(200000);
			}

			if (count($allWeixin) > 0) {
				foreach ($allWeixin as $weixinInfo) {
					$wxid = $weixinInfo['wxid'];
					$faceUrl = $weixinInfo['face_url'];

					$this->getFaceByUrl($wxid, $faceUrl);
				}
				$this->mysql->batchInsert('weixin_main', $allWeixin);
			}
		} else {
			$weixinInMysql = $this->getAllWeixin();
			$weixinUrl = $str;

			$urlParse = parse_url($weixinUrl, PHP_URL_QUERY);
			parse_str($urlParse);
			if (!strstr($urlParse, '__biz=') || !strstr($urlParse, 'mid=') || !strstr($urlParse, 'idx=') || !strstr($urlParse, 'sn='))
				return ['state'=>false, 'msg'=>'非微信文章url'];
			if (array_key_exists($__biz, $weixinInMysql)) {
				$wxDetail = $weixinInMysql[$__biz];
				return ['state'=>true,'msg'=>'添加成功','wxid'=>$wxDetail['wxid']];
			}

			$content = $this->getArticleByUrl($weixinUrl);
			$weixinInfo = $this->getArticleWeixinInfo($content);

			$weixinInfo['biz'] = $__biz;
			$weixinInfo['ctime'] = time();

			$wxid = $weixinInfo['wxid'];
			$faceUrl = $weixinInfo['face_url'];

			$this->getFaceByUrl($wxid, $faceUrl);
			if (is_numeric($this->mysql->insert('weixin_main', $weixinInfo)))
				return ['state'=>true,'msg'=>'添加成功','wxid'=>$wxid];
			else
				return ['state'=>false,'msg'=>'添加失败'];
		}
	}

	public function getWeixinCount()
	{
		$query = "select count(*) as sum from weixin_main where isdel = 'N'";
		$rs = $this->mysql->fetchFirst($query);
		return $rs['sum'];
	}

	public function getWeixinList($skip=0, $limit=0, $flag = 1,$order='0')
	{
		$orderby = '';
		
		if($order==1){
			$orderby = ' order by id desc';
			
		}
		if ($flag == 1) {
			if ($skip == 0 && $limit == 0)
				$query = "select * from weixin_main where isdel = 'N' and biz is not null{$orderby}";
			else
				$query = "select * from weixin_main where isdel = 'N' and biz is not null{$orderby} limit $skip, $limit";
		} else {
			if ($skip == 0 && $limit == 0)
				$query = "select * from weixin_main where isdel = 'N' and flag = $flag{$orderby}";
			else
				$query = "select * from weixin_main where isdel = 'N' and flag = $flag limit $skip, $limit";
		}

		$weixinInfos = $this->mysql->select($query);
		if (count($weixinInfos) == 0)
			return [];
		foreach ($weixinInfos as $value) {
			if (!is_null($value['cid']))
				$cidArr[] = $value['cid'];
		}
		$cidArr = array_unique($cidArr);
		$query = "select a.id as id, a.name as second_category, b.name as first_category from weixin_second_category as a left join weixin_first_category as b on a.fid = b.id where a.isdel = 'N' and b.isdel = 'N' and a.id in (" . implode(',', $cidArr) . ')';
		$rs = $this->mysql->select($query);
		foreach ($rs as $value) {
			$id = $value['id'];
			unset($value['id']);
			$categoryArr[$id] = $value;
		}

		$weixinList = [];
		foreach ($weixinInfos as $value) {
			$value['category'] = is_null($value['cid']) ? 'null' : $categoryArr[$value['cid']];
			if ($value['flag'] == 0) {
				$value['auth'] = '正在同步...';
				$value['face_wxid'] = 'wait_8888';
			}
			$weixinList[] = $value;
		}

		return $weixinList;
	}

	public function getWeixinExtList()
	{
		$weixinLists = $this->getWeixinList();
		foreach ($weixinLists as $value) {
			$weixinIds[] = "'{$value['wxid']}'";
		}
		$query = "select a.wxid, a.sogouid, a.ext, b.name as category from weixin_main as a left join weixin_mp_category as b on a.group_id = b.id where wxid in (" . implode(',', $weixinIds) . ")";
		$rs = $this->mysql->select($query);
		return $rs;
	}

	public function getCategories()
	{
		$query = "select a.id as id, a.name as second_category, b.id as fid, b.name as first_category,b.norder from weixin_second_category as a left join weixin_first_category as b on a.fid = b.id where a.isdel = 'N' and b.isdel = 'N' order by a.norder";
		$rs = $this->mysql->select($query);
		
		foreach ($rs as $value) {
			$categoryInfos[$value['id']] = $value;
		}

		return $categoryInfos;
	}

	public function getCategoryBySecondId($ids)
	{
		if (is_string($ids)) {
			$query = "select a.id as id, a.name as second_category, b.id as fid, b.name as first_category from weixin_second_category as a left join weixin_first_category as b on a.fid = b.id where a.id = $ids and a.isdel = 'N' and b.isdel = 'N'";
			return $this->mysql->fetchFirst($query);
		} else {
			$query = 'select a.id as id, a.name as second_category, b.id as fid, b.name as first_category from weixin_second_category as a left join weixin_first_category as b on a.fid = b.id where a.id in (' . implode(',', $ids) . ") and a.isdel = 'N' and b.isdel = 'N'";
			$rs = $this->mysql->select($query);
			foreach ($rs as $value) {
				$data[$value['id']] = $value;
			}
			return $data;
		}
	}

	public function getSecondCategorybyFirstId($id)
	{
		$query = "select * from weixin_second_category where fid = $id and isdel = 'N'";
		$rs = $this->mysql->select($query);
		foreach ($rs as $value) {
			$data[$value['id']] = $value;
		}
		return $data;
	}

	public function getWxidsByCategoryIdOnlyId($id) {
		$query = "select wxid, wxname from weixin_main where cid = $id and isdel = 'N'";
		$rs = $this->mysql->select($query);
		return $rs;
	}

	public function getWxidsByCategoryId($id)
	{
		// $key = "expire:weixin:getWxidsByCategoryId:$id";
		// $wxidInfos = $this->redis->get($key);
		// if (!$wxidInfos) {
			$query = "select * from weixin_main where cid = $id and isdel = 'N'";
			$rs = $this->mysql->select($query);
			return $rs;
			// $wxidInfos = json_encode($rs);

		// 	$this->redis->set($key, $wxidInfos);
		// }

		// return json_decode($wxidInfos, true);
	}

	public function getFirstCategory()
	{
		$query = "select * from weixin_first_category where isdel = 'N'";
		return $this->mysql->select($query);
	}

	public function checkCategoryNeedByIds($cid)
	{
		if (is_array($cid))
			$query = 'select id from weixin_main where cid in (' . implode(',', $cid) . ") and isdel = 'N'";
		else
			$query = "select id from weixin_main where cid = $cid and isdel = 'N'";

		$rs = $this->mysql->fetchFirst($query);
		if (count($rs) > 0)
			return true;
		else
			return false;
	}

	public function get_total_count()
	{
		// $key = 'expire:weixin:get_total_count';
		// $totalCount = $this->redis->get($key);
		
		// if (!$totalCount) {
			$rs = $this->mysql->fetchFirst('select * from article_all order by ctime desc');
			$totalCount = json_encode($rs);
			$this->redis->set($key, $totalCount);
		// }
		return json_decode($totalCount, true);
	}

	public function getReadKeyInfo()
	{
		$redis = n_api('redis')->scrapy;
		$rs = $redis->keys('weixinKeyInfo*');
		$keyInfo = [];
		
		foreach ($rs as $val) {
			$key = substr($val, strlen('scrapy:'));
			$keyInfo[md5($key)] = json_decode($redis->get($key), true);
		}
		ksort($keyInfo);
		$finaNeed = array_slice($keyInfo, 2);
		return $finaNeed;
	}

	public function getReadKeyInfoInside()
	{
		$redis = n_api('redis')->scrapy;
		$rs = $redis->keys('weixinKeyInfo*');
		$keyInfo = [];
		
		foreach ($rs as $val) {
			$key = substr($val, strlen('scrapy:'));
			$keyInfo[md5($key)] = json_decode($redis->get($key), true);
		}
		ksort($keyInfo);
		$finaNeed = array_slice($keyInfo, 0, 1);
		return $finaNeed;
	}

	public function getReadKeyInfoEvgo()
	{
		$redis = n_api('redis')->scrapy;
		$rs = $redis->keys('weixinKeyInfo*');
		$keyInfo = [];
		
		foreach ($rs as $val) {
			$key = substr($val, strlen('scrapy:'));
			$keyInfo[md5($key)] = json_decode($redis->get($key), true);
		}
		ksort($keyInfo);
		$finaNeed = array_slice($keyInfo, 1, 1);
		return $finaNeed;
	}

	public function getArticleByUrl($url)
	{
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36');
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
			'Accept-Language: zh-CN,zh;q=0.8',
			'Cache-Control: max-age=0',
			'Connection: keep-alive',
			'Host: mp.weixin.qq.com'
		]);

		$rs = curl_exec($ch);
		return $rs;
	}

	public function getArticleWeixinInfo($content)
	{
		preg_match("/hd_head_img : \"(.*)\"\|\|/ui", $content, $out);
		$rs['face_url'] = $out[1];

		n_api('phpquery')->phpQuery();
		phpQuery::newDocument($content);

		$rs['nickname'] = addslashes(pq('strong.profile_nickname')->text());
		$metaValue = pq('span.profile_meta_value');
		foreach ($metaValue as $value) {
			$tmp[] = pq($value)->text();
		}
		$wxid = $tmp[0];
		if (strlen($wxid) == 0) {
			preg_match("/var user_name = \"(.*)\";/ui", $content, $out);
			$wxid = $out[1];
		}

		$rs['wxid'] = addslashes($wxid);
		$rs['desc'] = addslashes($tmp[1]);

		return $rs;
	}

	public function checkExits($wxid)
	{
		$query = "select id from weixin_main where wxid = '$wxid'";
		$rs = $this->mysql->fetchFirst($query);
		if (count($rs) > 0)
			return true;
		else
			return false;
	}

	public function addWeixin($wxid, $wxname, $desc, $groupId, $biz, $face_url)
	{
		$data['wxid'] = $wxid;
		$data['wxname'] = $wxname;
		$data['description'] = $desc;
		$data['cid'] = $groupId;
		$data['ctime'] = time();
		$data['biz'] = $biz;
		$data['face_url'] = $face_url;

		$this->mysql->insert('weixin_main', $data);
	}
	
	public function getWxDetail($wxids)
	{
		if (is_string($wxids)) {
			$query = "select * from weixin_main where wxid = '$wxids' and isdel = 'N'";
			$weixinInfos = $this->mysql->fetchFirst($query);
			if (count($weixinInfos) == 0)
				return [];
			if ($weixinInfos['flag'] == 0) {
				$weixinInfos['auth'] = '正在同步...';
				$weixinInfos['face_wxid'] = 'wait_8888';
			}
			$cid = $weixinInfos['cid'];
			$categoryInfos = $this->getCategoryBySecondId($cid);
			$weixinInfos['sid'] = $categoryInfos['id'];
			$weixinInfos['fid'] = $categoryInfos['fid'];
			$weixinInfos['groupName'] = $categoryInfos['second_category'];
			$weixinInfos['groupNameFirst'] = $categoryInfos['first_category'];
			return $weixinInfos;
		} else {
			if (count($wxids) == 0)
				return [];

			foreach ($wxids as $wxid)
				$wxidArr[] = "'$wxid'";

			$query = 'select * from weixin_main where wxid in (' . implode(',', $wxidArr) . ") and isdel = 'N'";
			$weixinInfos = $this->mysql->select($query);
			foreach ($weixinInfos as $weixinInfo) {
				$cidArr[] = $weixinInfo['cid'];
			}
			$categoryInfos = $this->getCategoryBySecondId($cidArr);

			$data = [];
			foreach ($weixinInfos as $weixinInfo) {
				$weixinInfo['sid'] = $categoryInfos[$weixinInfo['cid']]['id'];
				$weixinInfo['fid'] = $categoryInfos[$weixinInfo['cid']]['fid'];
				$weixinInfo['groupName'] = $categoryInfos[$weixinInfo['cid']]['second_category'];
				$weixinInfo['groupNameFirst'] = $categoryInfos[$weixinInfo['cid']]['first_category'];
				if ($weixinInfo['flag'] == 0) {
					$weixinInfo['auth'] = '正在同步...';
					$weixinInfo['face_wxid'] = 'wait_8888';
				}
				$data[] = $weixinInfo;
			}
			return $data;
		}
	}

	public function getwxInfo($wxids){
		return $this->mysql->selectIndex("select * from weixin_main where wxid in('".implode("','",$wxids)."')",'wxid');
	}
	public function search($kw){
		return $this->mysql->select("select * from weixin_main where wxname like '%{$kw}%'");
	}



	public function numMore($num,$refer = 10000){

		$topNum = floor($num/$refer);

		$leftNum = ($num/$topNum*10)%$refer;
		if($topNum>=1 && $leftNum==1){
			return "{$topNum}w+";
		}else{
			return $num;
		}
	}


	public function getAllWeixin() {
		$query = "select * from weixin_main where isdel = 'N' and flag = 0 order by ctime desc";
		$rs = $this->mysql->select($query);

		$data = [];
		foreach ($rs as $value) {
			$data[$value['biz']] = $value;
		}
		return $data;
	}

	public function getFaceByUrl($wxid, $url) {
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36');
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
			'Accept-Language: zh-CN,zh;q=0.8',
			'Cache-Control: max-age=0',
			'Connection: keep-alive',
			'Host: mp.weixin.qq.com'
		]);

		$rs = curl_exec($ch);
		curl_close($ch);
		
		$path = '/opt/webapps/weixin/static/weixin_face/';
		$imgPath = $path . $wxid . '.jpg';
		if (!file_exists($imgPath)) {
			$fp = @fopen($imgPath, 'a');
			fwrite($fp, $rs);
			fclose($fp);
		}
	}
}